package moe.useraccount.Controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import moe.useraccount.pojo.useraccounts;
import moe.useraccount.repo.UserRepository;
import moe.useraccount.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.Optional;

@Tag(name = "UserAPI",description = "user接口")
@RestController
public class UserController {
    @Autowired
    UserRepository userRepository;
    public UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
    @Operation(method = "GET",description = "创建一个新用户")
    @GetMapping("/restful/user/register")
    public Result<?>  register(@Parameter String name,@Parameter String password,@Parameter String phone) {
        useraccounts temp=new useraccounts();
        temp.setName(name);
        temp.setPassword(password);
        temp.setScore(0);
        temp.setPhone(phone);
        temp.setLevel(0);
        userRepository.save(temp);
        return Result.ok(temp);
    }
    @Operation(method = "GET",description = "用户登录")
    @GetMapping("/restful/user/login")
    public Result<?>  login(@Parameter Long id,@Parameter String password) {
        Optional<useraccounts> temp = userRepository.findById(id);
        if(temp.isPresent()){
            if(temp.get().getPassword().equals(password))
            {
                return Result.ok(temp);
            }
            else
                return Result.error(204, "密码错误");
        }
        else
            return Result.error(204, "未找到用户");
    }
    @Operation(method = "GET",description = "返回用户信息")
    @GetMapping(path = "/restful/user/check")
    public Result<?> check(@Parameter Long id) {
        Optional<useraccounts> temp = userRepository.findById(id);
        if(temp.isPresent())
            return Result.ok(temp);
        else
            return Result.error(204, "未找到用户");

    }
    @Operation(method = "GET",description = "订单完成后修改积分和等级")
    @GetMapping("/restful/user/finish")
    public Result<?>  finish(@Parameter Long id,@Parameter float distance) {
        Optional<useraccounts> temp = userRepository.findById(id);
        if(temp.isPresent()){
            float score=temp.get().getScore();
            temp.get().setScore(score+distance);
            temp.get().setLevel((int)(score+distance)/8);
            userRepository.save(temp.get());
            return Result.ok(temp);
        }
        else
            return Result.error(204, "未找到用户");
    }



}
